package com.hnu.store.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

public class CutImage {

  public static BufferedImage[] splitImage(String originalImg,int rows,int cols) throws IOException {

    // 读入大图
    File file = new File(originalImg);
    FileInputStream fis = new FileInputStream(file);
    BufferedImage image = ImageIO.read(fis);
    //  文件类型jpg,png等
    String fileType = originalImg.substring(originalImg.indexOf('.')+1);

    // 分割成rows * cols个小图
    int chunks = rows * cols;

    // 计算每个小图的宽度和高度
    int chunkWidth = image.getWidth() / cols;
    int chunkHeight = image.getHeight() / rows;

    int count = 0;
    BufferedImage imgs[] = new BufferedImage[chunks];
    for (int x = 0; x < rows; x++) {
      for (int y = 0; y < cols; y++) {
        //设置小图的大小和类型
        imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

        //写入图像内容
        Graphics2D gr = imgs[count++].createGraphics();
        gr.drawImage(image, 0, 0,
            chunkWidth, chunkHeight,
            chunkWidth * y, chunkHeight * x,
            chunkWidth * y + chunkWidth,
            chunkHeight * x + chunkHeight, null);
        gr.dispose();
      }
    }

    // 输出小图
//    int start = Integer.parseInt(id)+1;
//    for (int i = 0; i < imgs.length; i++) {
//
//      ImageIO.write(imgs[i], fileType, new File("D:\\IDEA\\IdeaProjects\\store\\nft\\" + i +'.' +fileType));
//    }
    System.out.println("完成分割！");
    return imgs;
  }
}
